<?php
/*
待完成功能：获取sku
*/
set_time_limit(0);
//http://bbs.csdn.net/topics/390601967
	// define(DBHOST,"127.0.0.1");	 //数据库连接地址
	// define(DBUSER,"root");    //数据库用户名
	// define(DBPW,"123");      //数据库密码
	
	define(DBHOST,"192.168.0.88");	 //数据库连接地址
	define(DBUSER,"root");    //数据库用户名
	define(DBPW,"bidxi123");      //数据库密码
	
	define(DBNAME,"erp");     //数据库名
	mysql_connect(DBHOST,DBUSER,DBPW) or die ("connect abort.");
	mysql_select_db(DBNAME) or die ("database doesn't exit.");
	mysql_query("SET NAMES utf8");

	ob_end_flush();
	$http = new util_curl();
	echo $proxy_ip=proxy_ip();
	$http->set_proxy($proxy_ip);
	$response=$http->get("http://www.yantan.cc/ip.php");//http://kojiki.server.ne.jp/etc/pj235.cgi
	echo $response['content'];
	 exit;


function proxy_ip()
{
$ip_all_txt="
83.244.110.3:8080
84.40.120.192:8080
85.114.141.191:80
85.132.67.5:3128
86.99.66.246:443
86.100.50.7:8080
86.111.144.194:3128
86.120.196.242:8080
87.98.216.22:3128
88.249.230.31:8080
89.200.252.149:3128
91.99.101.218:80
91.121.182.155:3128
91.188.39.14:8888
91.203.140.46:3128
94.20.20.135:3128
94.20.20.136:3128
95.38.112.35:8080
95.65.58.61:443
95.154.87.18:3128
95.163.15.125:3128
96.44.157.204:7808
96.44.157.204:8089
101.4.60.101:80
103.3.79.114:8080
103.4.175.82:3128
103.8.221.253:8080
103.29.150.5:3128
106.187.103.77:3128
107.6.112.242:3128
109.73.68.233:7808
109.74.57.155:3128
109.175.6.192:8080
109.185.116.199:8080
109.194.65.175:3128
109.195.34.64:8080
109.238.189.252:8080
110.4.24.173:80
110.84.129.27:8888
110.93.195.238:8080
110.153.9.250:80
110.173.49.18:3128
111.1.32.53:82
111.1.32.53:8080
111.1.32.124:83
111.1.32.124:84
111.1.36.24:80
111.1.36.25:80
111.1.36.26:80
111.1.36.27:80
111.1.36.27:82
111.1.36.133:80
111.1.36.163:80
111.1.36.165:80
111.1.36.166:80
111.1.36.166:81
111.1.36.166:82
111.1.36.166:83
111.1.55.18:8080
111.11.27.196:80
111.47.92.226:8080
111.92.180.3:3128
111.94.149.249:8080
111.161.64.141:80
111.161.64.152:80
111.161.126.87:8080
111.161.126.88:8080
111.161.126.93:8080
111.206.81.248:80
112.90.146.76:3128
112.95.244.57:80
112.175.251.57:8080
113.9.163.21:8080
114.80.91.165:7780
114.80.91.166:7780
114.80.91.167:7780
114.80.91.181:7780
114.80.115.150:80
114.80.136.112:7780
114.104.203.3:80
114.104.203.3:81
114.104.203.12:80
114.104.203.12:81
114.141.162.53:8080
115.29.190.171:3128
115.84.179.93:80
115.85.64.122:8080
";
$ip_all=array_filter(explode("\n",trim($ip_all_txt)) );
//print_r($ip_all);
return $ip_all[rand(0,count($ip_all))];
}

$query=mysql_query("SELECT * from shuadan_orders where id=2512  order by dateline asc");//and status=1
while($row = mysql_fetch_array($query)){
			sleep_rand();
			if(!$row[sid] || ((time()-3600)>$row['sid_addtime']) ){
				$sid=get_jd_sid($row['id'],$row['username'],$row['passwd']);
			} //sid超时
			else{
				$sid=$row[sid];
			}
			if($sid){
				$result=get_jd_confirm($row['order_id'],$sid);
			}
			echo $result['content'];
			preg_match('/操作失败,请稍候再试/is',$result['content'],$failed);
			
			preg_match('/操作成功/is',$result['content'],$success);
			//echo $match[0];
			if(stristr($failed[0],"操作成功"))
			{
				mysql_query("update shuadan_orders set status=2 where id ={$row[id]} ");
			}
			if(stristr($failed[0],"操作失败"))
			{
				mysql_query("update shuadan_orders set status=-1 where id ={$row[id]} ");
			}			
		
	exit;
}
/*
确认订单
*/
function get_jd_confirm($order_id,$sid){
	global $http;
	!$sid && error('No sid!');
	!$order_id && error('No order_id!');
	$referurl="http://m.jd.com/user/confirmSelect.action?orderId=$order_id&sid=$sid";
	$get_url="http://m.jd.com/user/confirmGoods.action?orderId=$order_id&sid=$sid";
	$response = $http->get($get_url,$referurl);
	return $response;
}
function show_detail(){


$query=mysql_query("SELECT * from shuadan_orders where status=-2 and id=2448 order by id asc");
while($row = mysql_fetch_array($query)){
			$referurl ="http://m.jd.com/user/home.action?sid=".$row['sid'];
			$get_url="http://m.jd.com/user/myorders.action?sid=".$row['sid'];
			$response = $http->get($get_url,$referurl);
			!$response['content'] && exit("error");
			preg_match("/{$row['order_id']}.+?href\s?=\s?\"(.+?)\"/is",$response['content'],$match);
			//echo $response['content'];
			//print_r($match)."<br />";exit;
			$response = $http->get("http://m.jd.com".$match[1],$referurl);
			//echo $response['content'];
			echo <<<R
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> 京东 </title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;"/>	
	<base href="http://item.jd.com" target="_blank" />	
	</head> <body>		
R;
//匹配商品详情
		/*	preg_match_all('/<div\s+class="content1"\s?>(.+?)<div\s+class="ftop"\s?>/si',$response['content'],$match2); */ 

//http://m.jd.com/user/confirmSelect.action?orderId=979666750&sid=78d5b8ca58c961396c0b8e04f2c839ee
			preg_match_all('/<span>\s?订单商品\s?<\/span>\s?<\/div>(.+?)<div\s+style="margin-top\:5px;"\s?>/si',$response['content'],$match2);	//匹配商品
			//print_r($match2);
			$value3=preg_replace('/<div style="margin-top:5px;">.*?<\/div>/si','',$match2[1][0]);
			$value3=preg_replace('/\/product\/(\d+)\.html\?sid=[a-z0-9]{32}/si','/$1.html',$value3);	
			echo $value3;
			flush();
}
}



//登陆京东用户，获取sid
function get_jd_sid($id,$username,$passwd)
{
			global $http;
			$loginUrl ="http://m.jd.com/user/doLogin.action?v=w";
			$fields ="returnurl=http%3A%2F%2Fm.jd.com%2Fuser%2Fmyorders.action%3Fsid%3Dnull&username={$username}&password={$passwd}&btnLogin=%E7%99%BB%E5%BD%95&v=t";
			$response = $http->post($loginUrl,$fields,$referurl="http://m.jd.com/user/login.action");
			$curl_info=$response['curl_info'];
			if(stristr($curl_info['url'],'sid')){
				list(,$sid)=explode('sid=',$curl_info['url']);	
			}else{
				$sid='';
			}
			$sid && mysql_query("update shuadan_orders set status=-2,sid='".addslashes($sid)."',sid_addtime={$response['dateline']} where id ={$id} ");
			echo "update shuadan_orders set status=-2,sid='".addslashes($sid)."',sid_addtime={$response['dateline']} where id ={$id} <br />";
			flush();
			return $sid;		
}

function sleep_rand(){ sleep(rand(3,5)); }
function rm_space($str){	return preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/","",$str); } 
function error($msg){
	exit($msg.'<br />');
}
class util_curl {
    var $headers;
    var $compression;
    var $cookie_file;
    public $proxy;
	var $cookie_jd;
    function util_curl($is_cookie=TRUE,$cookie_address='cookies.txt',$header = array(),$compression='gzip',$proxy='') {
        if(empty($header))
        {
            $this->headers[] = 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
            $this->headers[] = 'Connection: Keep-Alive';
            //$this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
        }
        $this->compression=$compression;
        //$this->proxy=$proxy;
        $this->is_cookie=$is_cookie;
        if ($this->is_cookie == TRUE) $this->make_cookie($cookie_address);
    }
 	function set_proxy($proxy){
		 $this->proxy=$proxy;
	}
    function make_cookie($cookie_address) {
		$tmp_filepath=realpath('./').'/'.$cookie_address;
        if (file_exists($tmp_filepath)) {
			$this->cookie_file=$tmp_filepath;
        }
		else{
            if($h = fopen($tmp_filepath,'w')){
                $this->cookie_file=$tmp_filepath;
                fclose($h);
            } else {
                $this->error('The cookie file could not be opened. Make sure this directory has the correct permissions');
            }
        }
	
    }
	function user_agent(){
	$ua=array(
	'0'=>'Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1',
	'1'=>'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
	'2'=>'Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19',
	'3'=>'Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25',
	'4'=>'Mozilla/5.0 (Android; Mobile; rv:14.0) Gecko/14.0 Firefox/14.0',
	'5'=>'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',//ie7
	'6'=>'Mozilla/5.0 (Windows NT 6.1; Intel Mac OS X 10.6; rv:7.0.1) Gecko/20100101 Firefox/7.0.1',
	// '7'=>'',
	// '8'=>'',
	// '9'=>'',
	// '10'=>'',
	);
		$suiji=rand(0,6);
		return $ua[$suiji];
	}
    function post($url,$data,$refer){
        $curl = curl_init(); // 启动一个CURL会话
        //$this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=GBK';
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);
		if(isset($this->proxy)) curl_setopt ($curl, CURLOPT_PROXY, $this->proxy);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent()); // 模拟用户使用的浏览器
        //curl_setopt($curl, CURLOPT_NOBODY, 0);	//不获取内容
        if ($this->is_cookie == TRUE) curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookie_file);
		if ($this->is_cookie == TRUE) curl_setopt($curl, CURLOPT_COOKIEJAR, $this->cookie_file);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
		if(!isset($refer)){curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
		}else{curl_setopt($curl, CURLOPT_REFERER, $refer);	}
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $result['content']=curl_exec($curl); // 执行操作 $curl_info=
//preg_match_all('/Set-Cookie:(.*)Path\=\//iU',$curl_info,$str); //正则匹配
//print_r($str[0]); //获得COOKIE（SESSIONID）
		$curl_info=curl_getinfo($curl);	//获取请求头信息
		if($curl_info['http_code']!='200')	//判断状态码 决定是否重试
		{
			sleep(5);	//稍后重试
			curl_exec($curl); // 执行操作
			$curl_info=curl_getinfo($curl);
		}

		$result['curl_info']=$curl_info;
		$result['dateline']=time();
        if (curl_errno($curl)) {
           // return 'Error'.curl_error($curl);	//抓取异常
			return FALSE;
        }
        curl_close($curl); // 关闭CURL会话
        return $result; // 返回数据
    }
    function get($url,$refer){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        //$this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=GBK';
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); // 模拟用户使用的浏览器
        //curl_setopt($curl, CURLOPT_NOBODY, 0);
		//echo $this->proxy;
		if(isset($this->proxy)) curl_setopt ($curl, CURLOPT_PROXY, $this->proxy);
		//curl_setopt ($curl, CURLOPT_PROXYUSERPWD,'yushi:cxjb9ade');
		
		//curl_setopt ($curl, CURLOPT_PROXYTYPE,"CURLPROXY_SOCKS5");
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
		if(!isset($refer)){curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
		}else{curl_setopt($curl, CURLOPT_REFERER, $refer);	}
        //curl_setopt($curl, CURLOPT_POST, 0); // 发送一个常规的Post请求
        //curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 120); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if ($this->is_cookie == TRUE) curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookie_file);
        if ($this->is_cookie == TRUE) curl_setopt($curl, CURLOPT_COOKIEJAR, $this->cookie_file);		
        $result['content']=curl_exec($curl); // 执行操作
		$curl_info = curl_getinfo($curl); 
		if($curl_info['http_code']!='200')	//判断状态码 决定是否重试
		{
			sleep(5);	//稍后重试
			curl_exec($curl); // 执行操作
			$curl_info=curl_getinfo($curl);
		}
		$result['header']=$curl_info;
		$result['error']=curl_errno($curl);
        if ($result['error']) {
            return FALSE;
        }
		//preg_match_all('/^Set-Cookie: (.*?);/m', $curl_info, $tmp_filepath_cookie_jd); 
		//$this->cookie_jd=$tmp_filepath_cookie_jd[1];	
		//print_r($this->cookie_jd);		
        curl_close($curl); // 关闭CURL会话	
        return $result; // 返回数据
    }
 
}
